﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Utils.DB.OleDb;

namespace KQReport
{
    public class Depart
    {
        public Depart(DataRow row)
        {
            Id = Convert.ToInt32(row["DEPTID"]);
            ParentId = Convert.ToInt32(row["SUPDEPTID"]);
            Name = Convert.ToString(row["DEPTNAME"]);
        }
        public int Level { get; set; }
        public int Id { get; set; }
        public int ParentId { get; set; }
        public string Name { get; set; }
        public readonly List<Depart> Departs=new List<Depart>();

        public string Display
        {
            get { return Level == 0 ? Name : new string(' ', Level*2) + Name; }
        }

        public static List<Depart> LoadDeparts()
        {
            var ds = SqlHelperEx.ExecuteDataSet("select DEPTID,SUPDEPTID,DEPTNAME from DEPARTMENTS");
            var departs = new List<Depart>();
            foreach (DataRow row in ds.Tables[0].Rows)
                departs.Add(new Depart(row));
            var result = new List<Depart>();
            var root = departs.Where(p => p.ParentId == 0).ToArray();
            foreach (var depart in root)
            {
                depart.Level = 0;
                BuildChild(depart, departs);
                result.Add(depart);
            }
            return result;
        }

        private static void BuildChild(Depart depart, List<Depart> departs)
        {
            var childs = departs.Where(p => p.ParentId == depart.Id).ToArray();
            depart.Departs.AddRange(childs);
            foreach (var child in childs)
            {
                child.Level = depart.Level + 1;
                departs.Remove(child);
                BuildChild(child, departs);
            }
        }
    }
}